﻿<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="Shortcut Icon" href="../images/aecc.ico" type="image/x-icon" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../StaticFiles/element-plus-2.9.1/index.css" rel="stylesheet">
  <link href="../StaticFiles/nprogress/nprogress.min.css" rel="stylesheet">
  <link href="../styles/vue-page-common.css" rel="stylesheet">
  <script src="../Scripts/pollyfills/Array.prototype.flat.js"></script>
  <script src="../Scripts/pollyfills/ResizeObserver.js"></script>
  <script src="../StaticFiles/vue3/vue.global.prod.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/index.full.min.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/icons-vue.js"></script>
  <script src="../StaticFiles/element-plus-2.9.1/zh-cn.min.js"></script>
  <script src="../Scripts/axios.min.js"></script>
  <script src="../Scripts/axios.config.js"></script>
  <script src="../StaticFiles/nprogress/nprogress.min.js"></script>
  <script src="../Scripts/dayjs.min.js"></script>
  <title>MES报表授权</title>
  <style>
    .el-table--large .cell {
      padding: 0 10px !important;
    }
  </style>
</head>

<body>
  <div id="app" v-cloak>
    <vue3-report-header title="MES报表授权"></vue3-report-header>
    <div style="padding: 10px;" @keyup.enter="getData">
      <!-- 查询条件区 -->
      <el-form :inline="true" :model="dataObj.queryInfo" ref="queryInfoRef" :label-position="'left'"
        :disabled="dataObj.formDisabled">
        <el-form-item label="报表名称:">
          <el-autocomplete v-model.trim="dataObj.queryInfo.reportpagename" placeholder="请输入报表名称"
            :trigger-on-focus="false" style="width:400px;" :fetch-suggestions="getReportPageNameAsync"
            :value-key="'pagename'" :debounce="500">
          </el-autocomplete>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="'Search'" size="default" @click="getData">查询</el-button>
          <el-button type="success" :icon="'CirclePlus'" size="default" @click="addDialogOpen">新增</el-button>
          <el-button type="danger" :icon="'Delete'" size="default" @click="deleteItem">删除</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="dataObj.dataList" show-overflow-tooltip v-loading.fullscreen.lock="dataObj.loading"
        :element-loading-text="dataObj.loadingText" element-loading-background="rgba(0,0,0,0.8)"
        @selection-change="handlerSelectionChange" stripe border>
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column label="操作" width="165">
          <template #default="scope">
            <el-button type="primary" :icon="'CirclePlus'" size="small" @click="addItemUsersDialogOpen(scope.row)">添加
            </el-button>
            <el-button type="danger" :icon="'Remove'" size="small" @click="removeItemUserDialogOpen(scope.row)">移除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="reportpagename" label="报表名称"></el-table-column>
        <el-table-column prop="pageurl" label="报表路径"></el-table-column>
        <el-table-column prop="pagetype" label="报表类型" width="80"></el-table-column>
        <el-table-column prop="reportpageid" label="报表id" v-if="false"></el-table-column>
        <el-table-column prop="fullname" label="添加人" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="create_date" label="添加时间" width="160" :formatter="replaceDate"></el-table-column>
      </el-table>

      <!-- 添加报表项 -->
      <el-dialog title="添加报表项" v-model="dataObj.addDialogVisible" width="50%" @close="addDialogClose">
        <el-form :label-position="'top'" lable-width="100px" :rules="dataObj.rules" ref="ruleForm"
          :model="dataObj.auth_item">
          <el-form-item prop='reportpagename' label="报表名称:">
            <el-autocomplete v-model.trim="dataObj.auth_item.reportpagename" placeholder="请输入报表名称"
              :trigger-on-focus="false" :fetch-suggestions="getReportPageNameAsync" :value-key="'pagename'"
              :debounce="500" style="width:100%;">
            </el-autocomplete>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dataObj.addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addItem">确认</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 报表项添加人员对话框 -->
      <el-dialog title="添加权限人员" v-model="dataObj.grantDialogVisible" @close="addItemUserDialogClose">
        <el-form :model="dataObj.addItemUser" ref="addItemUserForm" :inline="true" :label-position="'top'">
          <el-form-item label="人员所属部门:" prop="factoryid">
            <el-select v-model="dataObj.addItemUser.factoryid" placeholder="请选择" filterable
              @change="factorySelectChange" style="width:578px;">
              <el-option v-for="f in dataObj.factoryList" :key="f.factoryname" :label="f.factoryname"
                :value="f.factoryid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 穿梭框 -->
        <el-transfer filterable filter-placeholder="请输入姓名检索" v-model="dataObj.willBeGrantUsers" :data="dataObj.userList"
          :titles="['未选', '已选']" :props="{key: 'employeeid',label: 'fullname'}">
        </el-transfer>

        <!-- 弹出窗底下按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dataObj.grantDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addItemUsers">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 报表项移除人员对话框 -->
      <el-dialog title="移除权限人员" v-model="dataObj.ungrantDialogVisible" @close="removeItemUserDialogClose">
        <!-- 穿梭框 -->
        <el-transfer filterable filter-placeholder="请输入姓名检索" v-model="dataObj.willBeUnGrantUsers"
          :data="dataObj.grantedUserList" :titles="['未选', '已选']" :props="{key: 'employeeid',label: 'fullname'}">
        </el-transfer>

        <!-- 弹出窗底下按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dataObj.ungrantDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="removeItemUsers">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
  <script type="module">
    import { fetchSuggestion, getFactory, getParams } from '../Scripts/hooks/useCommonMethod.js'
    import { replaceDate } from '../Scripts/hooks/format.js'
    import Vue3ReportHeader from '../Scripts/components/Vue3ReportHeader.js';
    const { createApp, reactive, ref, onMounted, watch } = Vue
    const { ElMessage, ElMessageBox, ElNotification } = ElementPlus
    const App = {
      setup() {
        const ruleForm = ref(null);
        const dataObj = reactive({
          loading: false,
          loadingText: '数据加载中...',
          total: 0,
          queryInfo: { reportpagename: '' },
          dataList: [],
          addDialogVisible: false,
          auth_item: { reportpagename: '', reportpageid: '' },
          rules: {
            reportpagename: [{ required: true, message: '报表名称不能为空', trigger: 'blur' }]
          },
          multipleSelection: [],
          userList: [],
          willBeGrantUsers: [],
          grantDialogVisible: false,
          addItemUser: {
            reportpageid: '',
            factoryid: ''
          },
          factoryList: [],
          ungrantDialogVisible: false,
          grantedUserList: [],
          willBeUnGrantUsers: [],
          removeItem: {
            reportpageid: ''
          },
          formDisabled: false
        });

        function getReportPageNameAsync(value, callback) {
          fetchSuggestion({ actionName: 'getReportPageAsync', name: 'pagename', value, callback, triggerLength: 1 });
        }

        // 查询分厂
        async function getFactory() {
          const { data: { data } } = await axios({
            method: 'POST',
            url: '../handler/report/CommonActionHandle.ashx?action=getFactory',
            data: { type: 'getFactory' }
          })
          dataObj.factoryList = data;
          dataObj.factoryList.unshift({ factoryid: '未指定部门', factoryname: '未指定部门', factorycode: '' });
        }

        // 查询分厂人员
        async function getFactoryUsers(factoryid) {
          const reportpageid = dataObj.addItemUser.reportpageid;
          const { data: { data } } = await axios({
            method: 'POST',
            url: '../handler/report/UserGrantAuthorization.ashx?action=getFactoryUsers',
            data: { type: 'getFactoryUsers', factoryid, reportpageid }
          });
          dataObj.userList = data.map((item) => {
            const { employeeid, fullname, disabled } = item;
            return { employeeid, fullname, disabled: disabled === 'true' }
          });
        }

        // 弹出框分厂选择变更
        async function factorySelectChange(factoryid) {
          dataObj.userList = [];
          dataObj.willBeGrantUsers = [];
          getFactoryUsers(factoryid);
        }

        // 查询数据
        async function getData() {
          dataObj.loading = true
          dataObj.loadingText = '数据加载中...'
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/UserGrantAuthorization.ashx?actions=getData',
            method: 'post',
            data: { ...dataObj.queryInfo, type: 'getData' }
          })
          dataObj.loading = false;
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.dataList = data;
        };

        // 表格选择事件
        function handlerSelectionChange(val) {
          dataObj.multipleSelection = val;
        }

        // 添加对话框打开
        function addDialogOpen() {
          dataObj.addDialogVisible = true
        }

        // 添加对话框关闭时
        function addDialogClose() {
          ruleForm.value.resetFields();
        }

        // 添加报表项
        function addItem() {
          ruleForm.value.validate(async (valid) => {
            if (!valid) {
              return ElMessage.error('必填项为空!');
            } else {
              // 验证所选报表是否存在且是否已被添加
              const { data: ckRes } = await axios.post('../handler/report/UserGrantAuthorization.ashx?action=checkSelectPageValid', {
                type: 'checkSelectPageValid',
                ...dataObj.auth_item
              });

              if (ckRes.total === 0) { return ElMessage.error('报表项不存在!'); }
              const { pageid, status } = ckRes.data[0];
              if (status === '已添加') {
                return ElMessage.error(`报表项【${dataObj.auth_item.reportpagename}】已存在，不能重复添加!`);
              }

              dataObj.auth_item.reportpageid = pageid;

              dataObj.loading = true;
              dataObj.loadingText = '数据保存中...';
              const { data: res } = await axios({
                url: '../handler/report/UserGrantAuthorization.ashx?actions=addItem',
                method: 'post',
                data: {
                  type: 'addItem',
                  employeeid: getParams('uid'),
                  ...dataObj.auth_item
                }
              });
              dataObj.loading = false;
              if (res.meta.status === 500) {
                return ElMessage.error(res.meta.msg);
              }
              if (res.total > 0) {
                ElMessage.success('保存成功');
                getData();
              } else {
                ElMessage.error('保存失败');
              }
              dataObj.addDialogVisible = false;
            }
          });
        }

        // 删除报表项
        function deleteItem() {
          if (dataObj.multipleSelection.length == 0) {
            return ElMessage.error('请至少勾选1条待删除的数据!');
          }

          ElMessageBox.confirm('你确认要永久删除所选的报表项吗? 删除后不可恢复, 是否继续?', '警告',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(async () => {
              dataObj.loading = true;
              dataObj.loadingText = '数据删除中...';
              const { data: { data, meta, total } } = await axios({
                url: '../handler/report/UserGrantAuthorization.ashx?actions=deleteItem',
                method: 'post',
                data: { type: 'deleteItem', items: dataObj.multipleSelection }
              });
              dataObj.loading = false;
              if (meta.status === 500) {
                return ElMessage.error(meta.msg);
              }
              if (total > 0) {
                ElMessage.success('删除成功');
                getData();
              } else {
                ElMessage.error('删除失败');
              }
            })
            .catch(() => { ElMessage.info('用户取消删除') });
        }

        // 添加权限人员对话框打开
        function addItemUsersDialogOpen(row) {
          dataObj.grantDialogVisible = true;
          dataObj.addItemUser.reportpageid = row.reportpageid;
          const { factoryid } = dataObj.addItemUser;
          if (!factoryid) { getFactoryUsers(factoryid); }
        }

        // 添加权限人员对话框关闭
        function addItemUserDialogClose() {
          dataObj.willBeGrantUsers = [];
          dataObj.addItemUser.factoryid = '';
        }

        // 添加权限人员
        async function addItemUsers() {
          if (dataObj.willBeGrantUsers.length == 0) {
            return ElMessage.error('请在左侧至少选择1项至右侧');
          }
          dataObj.loading = true
          dataObj.loadingText = '数据保存中...'
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/UserGrantAuthorization.ashx?actions=addItemUsers',
            method: 'POST',
            data: { type: 'addItemUsers', willBeGrantUsers: dataObj.willBeGrantUsers, reportpageid: dataObj.addItemUser.reportpageid }
          });
          dataObj.loading = false
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (total > 0) {
            ElMessage.success('添加成功!');
            dataObj.grantDialogVisible = false;
          }
        }

        // 移除权限人员对话框打开
        async function removeItemUserDialogOpen(row) {
          dataObj.ungrantDialogVisible = true;
          const { reportpageid } = row;
          dataObj.removeItem.reportpageid = reportpageid;
          dataObj.loading = true;
          dataObj.loadingText = '数据保存中...';
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/UserGrantAuthorization.ashx?actions=getItemGrantedUsers',
            method: 'POST',
            data: { type: 'getItemGrantedUsers', reportpageid }
          });
          dataObj.loading = false;
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          dataObj.grantedUserList = data;
        }

        // 移除权限人员对话框关闭
        function removeItemUserDialogClose() {
          dataObj.willBeUnGrantUsers = [];
          dataObj.removeItem.reportpageid = '';
        }

        // 移除权限人员
        async function removeItemUsers() {
          const reportpageid = dataObj.removeItem.reportpageid;
          if (dataObj.willBeUnGrantUsers.length == 0) {
            return ElMessage.error('请在左侧至少选择1项至右侧');
          }
          dataObj.loading = true
          dataObj.loadingText = '数据保存中...'
          const { data: { data, meta, total } } = await axios({
            url: '../handler/report/UserGrantAuthorization.ashx?actions=removeItemUsers',
            method: 'POST',
            data: { type: 'removeItemUsers', willBeUnGrantUsers: dataObj.willBeUnGrantUsers, reportpageid }
          });
          dataObj.loading = false;
          if (meta.status === 500) {
            return ElMessage.error(meta.msg);
          }
          if (total > 0) {
            ElMessage.success('移除成功!');
            dataObj.ungrantDialogVisible = false;
          }
        }

        onMounted(async () => {
          if (!getParams('uid')) {
            dataObj.formDisabled = true;
            return ElNotification.error({ title: '错误', message: '缺少用户信息!', duration: 0 });
          }

          const { data: { total } } = await axios.post('../handler/report/UserGrantAuthorization.ashx?action=isSuperAdmin', {
            type: 'isSuperAdmin',
            employeeid: getParams('uid')
          });

          if (total < 1) {
            dataObj.formDisabled = true;
            return ElNotification.error({ title: '错误', message: '当前用户无权使用该功能!', duration: 0 });
          }

          getFactory();
        })

        watch(() => dataObj.queryInfo, () => {
          dataObj.currentPage = 1;
        }, { deep: true })

        return {
          ruleForm,
          dataObj,
          getData,
          handlerSelectionChange,
          getReportPageNameAsync,
          addDialogOpen,
          addDialogClose,
          addItem,
          deleteItem,
          addItemUsersDialogOpen,
          factorySelectChange,
          addItemUserDialogClose,
          addItemUsers,
          removeItemUserDialogOpen,
          removeItemUserDialogClose,
          removeItemUsers,
          replaceDate
        }
      }
    };

    const app = createApp(App);
    app.use(ElementPlus, {
      locale: ElementPlusLocaleZhCn,
      size: 'large'
    });
    // 注册所有icon
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component)
    }
    app.component('vue3-report-header', Vue3ReportHeader);
    app.mount('#app');
  </script>
</body>

</html>